<template>
  <div class="app-container" style="padding:1vh 2vw">
    <div class="tab-container" style="margin: 6vh 2vw;">
      <div style="margin: 1vh 0;">
        <el-button type="primary" @click="handleUnread()" :size="handleSize()" icon="el-icon-edit">标记为未读</el-button>
        <el-button type="primary" @click="handleRead()" :size="handleSize()" icon="el-icon-edit">标记为已读</el-button>
        <el-button type="danger" @click="handleDelete()" :size="handleSize()" icon="el-icon-delete">删除</el-button>
      </div>

      <el-table
        ref="multipleTable"
        :data="feedbacksList"
        :row-key="getRowKeys"
        highlight-current-row
        style="width: 100%;"
        max-height="800"
        :size="handleSize()"
        tooltip-effect="light"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" min-width="50" max-width="70"/>
        <el-table-column fixed sortable prop="id" label="ID" max-width="200" min-width="70"/>
<!--        <el-table-column prop="name" label="发件人" max-width="200" min-width="100" />-->
        <el-table-column prop="content" label="内容" show-overflow-tooltip max-width="400" min-width="200"/>
        <el-table-column sortable prop="createdAt" label="时间" min-width="200" max-width="400">
          <template v-slot="scope">
            {{ formatToDatetime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" max-width="200" min-width="100">
          <template v-slot="{row,$index}">
            <el-badge :is-dot="row.status == 0" class="item">
              <el-button type="text" size="small" @click="handleSelect(row,$index)">查看</el-button>
            </el-badge>
          </template>
        </el-table-column>

        <el-row style="display: flex;justify-content: center;margin-top: 5vh">
          <el-col :xs="18" :sm="12" :md="12" :lg="8" :xl="6" style="display: flex;justify-content: center">
            <el-pagination
              v-show="total>0"
              background
              hide-on-single-page
              :pager-count="5"
              :current-page.sync="currentPage"
              :page-size="perPage"
              layout="prev, pager, next"
              :total="total"
              @prev-click="change"
              @next-click="change"
              @current-change="change">
            </el-pagination>
          </el-col>
        </el-row>
      </el-table>

      <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :fullscreen="device() === 'mobile'">
        <el-form ref="dataForm" :model="temp" :label-position="device() === 'mobile' ? 'top' : 'left' " label-width="70px" style="width: 400px; margin-left:20px;">
          <el-form-item label="活动标题" prop="activity">
            <el-input v-model="temp.activity" disabled style="width: 300px" />
          </el-form-item>
          <el-form-item label="活动评分" prop="rate">
              <el-rate
                v-model="temp.rate"
                :disabled="true"
                :max="5"
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                :low-threshold="2"
                :high-threshold="5"
                show-score
                style="display:inline-block;width: 300px"
              />
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <el-input v-model="temp.content" type="textarea" :rows="5" :disabled="true" style="width: 300px"/>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {changeFeedback, deleteFeedback} from '@/api/base/feedback'
import {indexFeedback} from "@/api/base/feedback";

const defaultFeedback = {
  id: undefined,
  createdAt: undefined,
  user: undefined,
  activity: undefined,
  rate: 0,
  content: '',
  status: 0
}

export default {
  data() {
    return {
      currentPage: 1,
      lastPage: 0,
      total: 0,
      perPage: 12,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        select: '查看'
      },
      multipleSelection: [],
      multipleSelectionId: [],
      multipleSelectionRate: [],
      temp: Object.assign({},defaultFeedback),
      feedbacksList: []
    }
  },
  created() {
    // 设置当前页为1
    this.currentPage = 1;
    // 从服务器端获取 反馈列表
    this.getFeedback();
  },
  methods: {
    // 获取反馈列表
    async getFeedback() {
      const currentPage = this.currentPage;
      const res = await indexFeedback({page: currentPage})
      // 获取数据
      this.feedbacksList = res.data.data
      this.currentPage = res.data.currentPage
      this.lastPage = res.data.lastPage
      this.total = res.data.total
      this.perPage = res.data.perPage
    },
    // 查看当前行反馈信息
    handleSelect(row) {
      // 复制当前行对象
      this.temp = Object.assign({}, row)
      this.temp.status = 1 // 设置状态为已读
      this.dialogFormVisible = true
      this.dialogStatus = 'select'
      changeFeedback({ id: row.id, status: "1", rate: row.rate }).then(async ()=> {
        this.getFeedback()
      })
    },
    // 标记为未读
    handleUnread() {
      for (let i = 0; i < this.multipleSelectionId.length; i++) {
        changeFeedback({id: this.multipleSelectionId[i], status: "0", rate: this.multipleSelectionRate[i]}).then(async () =>{
          this.getFeedback()
        }).catch(err => {
          console.error(err)
        });
      }
    },
    // 标记为已读
    handleRead() {
      for (let i = 0; i < this.multipleSelectionId.length; i++) {
        changeFeedback({id: this.multipleSelectionId[i], status: "1", rate: this.multipleSelectionRate[i]}).then(async () =>{
          this.getFeedback()
        }).catch(err => {
          console.error(err)
        });
      }
    },
    // 删除反馈
    handleDelete() {
      this.$confirm('是否移除选中反馈?', '警告', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
          for (let i = 0; i < this.multipleSelectionId.length; i++) {
            deleteFeedback({id: this.multipleSelectionId[i]}).then(async () => {
              this.getFeedback()
            }).catch(err => {
              console.error(err)
            });
          }
      })
    },
    // 返回设备类别
    device() {
      return this.$store.state.app.device
    },
    // 根据设备类型控制尺寸
    handleSize() {
      return this.$store.state.app.device === 'mobile' ? 'mini' : 'medium'
    },
    // 时间格式化方法
    formatToDatetime(isoString) {
      const date = new Date(isoString)
      if (isNaN(date.getTime())) {
        throw new Error('Invalid ISO 8601 date string')
      }
      const year = date.getFullYear()
      const month = (1 + date.getMonth()).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    // 换页
    change(e) {
      this.currentPage = e;
      // 获取数据
      this.getFeedback();
    },
    // 获取选中行信息
    handleSelectionChange(selection) {
      this.multipleSelection = selection
      this.multipleSelectionId = selection.map(item => item.id)
      this.multipleSelectionRate = selection.map(item => item.rate)
    },
    // 绑定当前row - key
    getRowKeys(row) {
      if (row !== null) {
        return row.id
      }
    },
    // 时间戳 转换为 时间单位
    timestampToTime(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      const hours = date.getHours().toString().padStart(2, '0');
      const minutes = date.getMinutes().toString().padStart(2, '0');
      const seconds = date.getSeconds().toString().padStart(2, '0');

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  }
}
</script>

<style scoped lang="scss">
.app-container {

  .tab-container {
  }
}

.item {
  margin-top: 10px;
  margin-right: 40px;
}
</style>


<!--{-->
<!--id: 1,-->
<!--name: '张三',-->
<!--content: '这是第一封测试邮件',-->
<!--time: '2022-01-01 12:00:00',-->
<!--createdAt: 1628757400,-->
<!--title: '星际探索之旅',-->
<!--rate: 5,-->
<!--status: 1-->
<!--}, {-->
<!--id: 2,-->
<!--name: '李四',-->
<!--content: '这是第二封测试邮件，关于活动我有以下建议……阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴阿巴',-->
<!--time: '2023-01-01 8:50:00',-->
<!--createdAt: 1628757400,-->
<!--title: '瑜伽与冥想课程',-->
<!--rate: 3.6,-->
<!--status: 0-->
<!--}-->
